package meijuli.com.join51.business.utils;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;

import meijuli.com.join51.business.app.MApplication;
import meijuli.com.join51.business.BuildConfig;
import meijuli.com.join51.business.activity.LoginActivity;
import meijuli.com.join51.business.model.ResArray;
import meijuli.com.join51.business.model.ResObj;
import com.jhx.common.utils.ToastUtil;

import retrofit2.Response;

/**
 * 请求接口后要调用这个方法
 * fail在onFailure中调用
 * <p>
 * onSuccess() 在 onResponse 中调用，返回ResObj的code值，
 * 可以根据需要在OnResponse中做相应处理
 * 返回0表示成功
 *
 * @author wenqin 2017-04-15 13:22
 */

public class CallUtils {

    public static void fail(Context context, Throwable t) {
        if (BuildConfig.DEBUG) {
            ToastUtil.getInstance().showToast(context, t.getMessage());
        } else {
            ToastUtil.getInstance().showToast(context, "网络访问异常");
        }
    }

    public static <T> int success(Context context, Response<T> response) {
        if (!response.isSuccessful()) {
            ToastUtil.getInstance().showToast(context, "网络访问异常");
            return response.code();
        }

        if (response.body() instanceof ResArray) {
            ResArray resArray = (ResArray) response.body();
            if (resArray.getCode() != 0) {
                ToastUtil.getInstance().showToast(context, resArray.getMsg());
                toLogin(context, resArray.getCode());
                return resArray.getCode();
            }
        }

        if (response.body() instanceof ResObj) {
            ResObj resObj = (ResObj) response.body();
            if (resObj.getCode() != 0) {
                ToastUtil.getInstance().showToast(context, resObj.getMsg());
                toLogin(context, resObj.getCode());
                return resObj.getCode();
            }
        }

        if (response.body() == null) {
            return -1;
        }
        return 0;
    }

    public static void toLogin(Context context) {
        toLogin(context, 8888);
    }

    public static void toLogin(Context context, int code) {
        if (code == 8888) {
            if (context == null) {
                context = MApplication.get();
            }
            Intent intent = new Intent(MApplication.get(), LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            if (context instanceof AppCompatActivity) {
                AppCompatActivity appCompatActivity = (AppCompatActivity) context;
                appCompatActivity.finishAffinity();
            }
        }
    }
}
